package com.flyee.utils
{
	import flash.display.DisplayObjectContainer;
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.errors.IOError;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.events.TimerEvent;
	import flash.net.URLRequest;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	import flash.utils.Timer;
	
	import mx.controls.ProgressBar;
	import mx.controls.ProgressBarMode;
	import mx.managers.PopUpManager;
	
	public class DepotLoader extends Loader
	{
		private var _loaderInfo:LoaderInfo = null;
		private var loadUrl:String = null;
			/**
		 * 连接次数
		 */
		private var progressCounter:int = 0;
		/**
		 * 加载进度时间监听
		 */
		private var progressTimer:Timer = null;
		/**
		 * 时间计数器
		 */
		private var timerCounter:int = 0;
		/**
		 * 连接失败次数计数器
		 */
		private var failedCounter:int = 0;
		/**
		 * 重新次数连接计数器
		 */
		private var reconnectNum:int = 0;
		
		private var rootContainer:DisplayObjectContainer = null;
		private var progressBar:ProgressBar = null;
		public function DepotLoader()
		{
		}
		
		/**
		 * 加载SWF 
		 * @param url 资源地址
		 * 
		 */		
		public function loadByURL(url:String,root:DisplayObjectContainer = null):void 
		{
			loadUrl = url;
			rootContainer = root;
			//var context:LoaderContext = new LoaderContext(false,ApplicationDomain.currentDomain,SecurityDomain.currentDomain);
			
			/** 加载到子域 */
			//context.applicationDomain = new ApplicationDomain(ApplicationDomain.currentDomain);
			
			initLoadEvent(this.contentLoaderInfo);
			try{
				this.load(new URLRequest(url));
				progressTimer = new Timer(1000);
				progressTimer.start();
				progressTimer.addEventListener(TimerEvent.TIMER, timerHandler);
			}catch(errot:Error){
				MyLog.error("depot load error!!!");
			}
		}
		
		/**
		 * 获取当前ApplicationDomain内的类定义
		 * 
		 * @param name 类名称，必须包含完整的命名空间,如 Grave.Function.SWFLoader
		 * @param info 加载swf的LoadInfo，不指定则从当前域获取
		 * @return 获取的类定义，如果不存在返回null
		 */
		public function getClassByName(className:String, info:LoaderInfo = null):Class 
		{
			try 
			{
				if (info == null) 
				{
					var domain:ApplicationDomain = this.contentLoaderInfo.applicationDomain;
					return domain.getDefinition(className) as Class;
				}
				return info.applicationDomain.getDefinition(className) as Class;
			} 
			catch (e:ReferenceError) 
			{
				return null;
			}
			return null;
		}
		
		private function showProgressBar():void{
			if (!progressBar)
			{
				progressBar=new ProgressBar();
				progressBar.mode = ProgressBarMode.MANUAL;
				//progressBar.x = (rootContainer.width - 190) / 2;
				//progressBar.y=(rootContainer.height - progressBar.height) / 2;
				//rootContainer.addChild(progressBar);
				PopUpManager.addPopUp(progressBar,rootContainer,false);
				PopUpManager.centerPopUp(progressBar);
			}
		}
		
		private function reload():void
		{
			var request:URLRequest = new URLRequest(this.loadUrl);
			try{
				this.clear();
				this.close();
			}catch(e:IOError){
				throw new Error("can not close this connect!!!");
			}
			try
			{
				
			var context:LoaderContext = new LoaderContext(false,ApplicationDomain.currentDomain);
			
			this.unload();
			this.load(request,context);
			}
			catch(error:Error)
			{
				trace("Unable to load requested document.");
			}

		}
			/**
		 * 控制重新连接服务器
		 * @param event
		 *
		 */
		private function timerHandler(event:TimerEvent):void
		{

			if (timerCounter == progressCounter)
			{
				//掉线需要重新连接
				failedCounter++;

				if (failedCounter == 3)
				{
					failedCounter = 0;
					reconnectNum++;
					reload();
				}

				if (reconnectNum == 5)
				{
					//网络断掉
					clearTimer();
				}
			}
			else
			{
				timerCounter = progressCounter;
			}
		}
		/**
		 * @private
		 * 监听加载事件
		 * 
		 * @param info加载对象的LoaderInfo
		 */
		private function initLoadEvent(info : LoaderInfo):void 
		{
			info.addEventListener(ProgressEvent.PROGRESS, this.onProgressEvent);
			info.addEventListener(Event.COMPLETE, this.loaderCompleteEvent);
			info.addEventListener(IOErrorEvent.IO_ERROR, this.onErrorEvent);
			info.addEventListener(SecurityErrorEvent.SECURITY_ERROR, this.onErrorEvent);
		}
		
		/**
		 * @private
		 * 移除加载事件
		 * 
		 * @param inft加载对象的LoaderInfo
		 */
		private function removeLoadEvent(info:LoaderInfo):void 
		{
			info.removeEventListener(Event.COMPLETE,loaderCompleteEvent);
			info.removeEventListener(ProgressEvent.PROGRESS,onProgressEvent);
			info.removeEventListener(IOErrorEvent.IO_ERROR,onErrorEvent);
			info.removeEventListener(SecurityErrorEvent.SECURITY_ERROR,onErrorEvent);
		}
		
		/**
		 * 加载完成事件 
		 * @param e
		 * 
		 */		
		private  function loaderCompleteEvent(e:Event):void 
		{
			var info:LoaderInfo = e.currentTarget as LoaderInfo;
			if(rootContainer){
				//rootContainer.removeChild(progressBar);
				PopUpManager.removePopUp(progressBar);
				progressBar = null;
			}
			_loaderInfo = info;
			removeLoadEvent(info);
			clearTimer();
			this.dispatchEvent(e);
		}
		
		/**
		 * 加载进度事件 
		 * @param e
		 * 
		 */		
		private function onProgressEvent(e:ProgressEvent):void 
		{
			progressCounter++;
			if(rootContainer){
				var loaded:int = e.bytesLoaded;
				var total:int = e.bytesTotal;
				showProgressBar();
				progressBar.setProgress(loaded,total);
				progressBar.label = "加载库文件  "+ Math.round((loaded/total)*100) + "%";
			}
			this.dispatchEvent(e);
		}
		
		/**
		 * 出错事件 
		 * @param e
		 * 
		 */		
		private function onErrorEvent(e:Event):void 
		{
			this.dispatchEvent(e);
		}
		private function clearTimer():void{
			reconnectNum = 0;
			progressCounter = 0;
			timerCounter = 0;
			progressTimer.stop();

			progressTimer.removeEventListener(TimerEvent.TIMER, this.timerHandler);
			progressTimer = null;
		}
		/**
		 *清楚函数 
		 * 
		 */		
		public function clear():void
		{
			
		}
	}
}